<template>
    <div class="container">
        <!-- 服务信息列表 -->
        <div v-for="(service, index) in services" :key="index">
            <div class="service-item">
                <div class="service-header">
                    <el-badge :type="service.status == '已完成' ? 'primary' : 'danger'" :offset="[20, 0]"
                        :value="service.status">
                
                        <div class="service-time">{{ service.submissionTime }}</div>
                    </el-badge>
                </div>
              <div class="service-content">
                    <div class="service-title">
                        <span>服务信息</span>

                    </div>
                    <div class="service-details">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务编号</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.id }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务状态</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.status }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务机构</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.homeinstitution.institutionname }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务团队</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.hometeam.name }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务医生</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.homedoctor.name }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务包</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.homeservicepackage.packageName }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务项目</span>
                                    &nbsp;&nbsp;
                                    <span>{{ service.homeServiceItem.itemName }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务地点</span> &nbsp;&nbsp;
                                    <span>{{ service.location }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务来源</span> &nbsp;&nbsp;
                                    <span>居民申请</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>提交时间</span> &nbsp;&nbsp;
                                    <span>{{ service.submissionTime }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>审核时间</span> &nbsp;&nbsp;
                                    <span>{{ service.auditTime }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>审核人</span> &nbsp;&nbsp;
                                    <span>{{ service.homeDoctor1.name }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务时间</span> &nbsp;&nbsp;
                                    <span>{{ service.appointmentTime }}</span>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="info-item">
                                    <span>服务备注</span> &nbsp;&nbsp;
                                    <span>{{ service.remark }}</span>
                                </div>
                            </el-col>
                        </el-row>

                    </div>
                </div>
            </div>
        </div>
        <!-- 底部按钮 -->
        <div class="button-group">
            <el-button type="primary" @click="handleAdd()">添加服务</el-button>
            <el-button @click="goBack">返回</el-button>
        </div>
    </div>
      <!-- 添加或修改服务记录对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="service_recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="居民姓名" prop="userId">
         <span>{{ props.username }}</span>
        </el-form-item>
        <el-form-item label="机构名称" prop="institutionId">
          <el-select v-model="form.organizationId" placeholder="请选择机构">
            <el-option v-for="dict in institutions" :key="dict.id" :label="dict.institutionname"
              :value="parseInt(dict.id)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队名称" prop="teamId">
          <el-select v-model="form.teamId" placeholder="请选择团队外键">
            <el-option v-for="dict in teams" :key="dict.id" :label="dict.name" :value="parseInt(dict.id)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生名称" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="请选择医生名称">
            <el-option v-for="dict in doctors" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务包" prop="packageId">
          <el-select v-model="form.packageId" placeholder="请选择服务包">
            <el-option v-for="dict in package_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务项目" prop="itemId">
          <el-select v-model="form.itemId" placeholder="请选择服务项目">
            <el-option v-for="dict in service_items" :key="dict.itemId" :label="dict.itemName"
              :value="parseInt(dict.itemId)">
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.itemId" placeholder="请输入服务项目(外键)" /> -->
        </el-form-item>
        <el-form-item label="服务状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择服务状态">
            <template v-for="dict in audit_tatus_five" >
              <el-option v-if="dict.value >= 3"
              :key="dict.value" 
              :label="dict.label"
              :value="parseInt(dict.value)">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="服务地点" prop="location">
          <el-select v-model="form.location" placeholder="请选择服务地点">
            <el-option v-for="dict in service_locations" :key="dict.value" :label="dict.label"
              :value=dict.value></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable v-model="form.appointmentTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="提交时间" prop="submissionTime">
          <el-date-picker clearable v-model="form.submissionTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择提交时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核时间" prop="auditTime">
          <el-date-picker clearable v-model="form.auditTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人id" prop="auditorId">
          <el-input v-model="form.auditorId" placeholder="请输入审核人id" readonly>
            {{ state.user.userName }}
          </el-input>
        </el-form-item>
        <el-form-item label="取消原因" prop="cancellationReason">
          <el-input v-model="form.cancellationReason" placeholder="请输入取消原因" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker clearable v-model="form.finishTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入服务备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { onMounted } from 'vue'
import { ref } from 'vue'
import { homeservicelist } from '@/api/resident/resident.js'
const { proxy } = getCurrentInstance();
const { years, audit_tatus_five, package_type, service_locations } = proxy.useDict('years', 'audit_tatus_five', 'package_type', 'service_locations');
const props = defineProps({
    userId: {
        type: Number,
    },
    username:{
        type: String,
    }
})

// 模拟服务信息数据
const services = ref([
  {
    id: '2021340001',
    time: '2020/10/09 10:09:09',
    status: '已完成',
    homeinstitution: { institutionname: '洛西社区卫生服务站' },
    hometeam: { name: '李明明团队' },
    homedoctor: { name: '李明明' },
    homeservicepackage: { packageName: '老年人服务包' },
    homeServiceItem: { itemName: '老年人服务包' },
    location: '洛西社区卫生服务站',
    submissionTime: '2020/10/09 10:09:09',
    auditTime: '2020/10/09 10:09:09',
    homeDoctor1: { name: '李明明' },
    appointmentTime: '2020/10/09 10:09:09',
    remark: '无'
  }
])

function gethomeservicelistInfo() {
    return new Promise((resolve, reject) => {
        homeservicelist(props.userId).then((res) => {
            console.log('gethomeservicelistInfo', res.data)
            let servicestemp = res.data;
            servicestemp.forEach(item => {
                audit_tatus_five.value.forEach(audit => {
                    if (item.status == audit.value) {
                        item.status = audit.label;
                    }
                })
              
                service_locations.value.forEach(location => {
                    if (item.location == location.value) {
                        item.location = location.label;
                    } 
                })
        item.time = formatDate(item.time);
        item.submissionTime = formatDate(item.submissionTime);
        item.auditTime = formatDate(item.auditTime);
        item.appointmentTime = formatDate(item.appointmentTime);
      });
            services.value = servicestemp;
            console.log(' services.value', services.value);
            resolve(res.data)
        }).catch((error) => {
            console.log('gethomeservicelistInfoerror', error);
        })
    })
}

// 定义一个函数用于将日期字符串转换为指定格式
function formatDate(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}


    // 模拟返回方法
    const goBack = () => {
        router.push({ path: 'resident' });
    }
    onMounted(async () => {
await gethomeservicelistInfo();
    })
    // 定义表单数据和规则


import { listService_record, getService_record, delService_record, addService_record, updateService_record } from "@/api/service_record/service_record";
import { useRouter } from "vue-router";
import { listDoctor } from "@/api/system/doctor";
import { listResident } from "@/api/resident/resident";
import { listInstitution } from "@/api/system/institution";
import { listItem } from "@/api/item/item";
import { listTeam } from "@/api/system/team";

import { getUserProfile } from "@/api/system/user";


const service_recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//  用户信息
const state = reactive({
  user: {},
  roleGroup: {},
  postGroup: {}
});
function getUser() {
  getUserProfile().then(response => {
    state.user = response.data;
    console.log(state.user);
    state.roleGroup = response.roleGroup;
    state.postGroup = response.postGroup;
  });
};

getUser();

// 定义一个service_items数组，用于存储服务项目数据
const service_items = ref([]);
// 定义一个方法、动态获取服务项目数据
function getService_items() {
  listItem().then(response => {
    service_items.value = response.rows;
    console.log(service_items.value);
  });
}
// 调用getService_items方法，获取服务项目数据
getService_items();

// 定义一个institutions数组，用于存储机构数据
const institutions = ref([]);
// 定义一个方法、动态获取机构数据
function getInstitutions() {
  listInstitution().then(response => {
    institutions.value = response.rows;
    // console.log(institutions.value);
  });

}
// 调用getInstitutions方法，获取机构数据
getInstitutions();

// 定义一个teams数组，用于存储团队数据
const teams = ref([]);
// 定义一个方法、动态获取团队数据
function getTeams() {
  listTeam().then(response => {
    teams.value = response.rows;
    console.log(teams.value);
  });
}
// 调用getTeams方法，获取团队数据
getTeams();


// 定义一个users数组，用于存储用户数据
const users = ref([]);
// 定义一个方法、动态获取用户数据
function getUsers() {
  listResident().then(response => {
    users.value = response.rows;
    console.log(users.value);
  });
}
// 调用getUsers方法，获取用户数据
getUsers();

// 定义一个doctors数组，用于存储医生数据
const doctors = ref([]);
// 定义一个方法、动态获取医生数据
function getDoctors() {
  listDoctor().then(response => {
    doctors.value = response.rows;
    // console.log(doctors.value);
  });
}
// 调用getDoctors方法，获取医生数据
getDoctors();
// 详情页跳转
const router = useRouter();
const handleDetail = (row) => {
  const ids = row.id;
  router.push({ path: 'servicexiangqing', query: { id: ids } });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    teamId: null,
    packageId: null,
    status: null,
    appointmentTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询服务记录列表 */
function getList() {
  loading.value = true;
  listService_record(queryParams.value).then(response => {
    // 过滤服务状态大于 2 的记录
    service_recordList.value = response.rows.filter(item => item.status === 3 || item.status === 4 || item.status === 5);
    // 更新 total 为过滤后的记录数
    total.value = service_recordList.value.length;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    organizationId: null,
    teamId: null,
    doctorId: null,
    packageId: null,
    itemId: null,
    status: null,
    location: null,
    appointmentTime: null,
    submissionTime: null,
    auditTime: null,
    auditorId: state.user.userName,
    cancellationTime: null,
    cancellationReason: null,
    finishTime: null,
    remark: null
  };
  proxy.resetForm("service_recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加服务记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getService_record(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改服务记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["service_recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.userId = props.userId;
        updateService_record(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          gethomeservicelistInfo();
        });
      } else {
        addService_record(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          gethomeservicelistInfo();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除服务记录编号为"' + _ids + '"的数据项？').then(function () {
    return delService_record(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service_record/service_record/export', {
    ...queryParams.value
  }, `service_record_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped lang="scss">
.container {
    padding: 20px;
}

.service-item {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 20px;
    padding: 20px;
}

.service-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.service-time {
    font-size: 14px;
    color: #666;
}

.service-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-size: 18px;
    font-weight: bold;
}

.service-details {
    display: flex;
    flex-wrap: wrap;
}

.info-item {
    margin-bottom: 30px;

}

.info-item span:first-child {
    font-size: 15px;
    /* 字体大小 */
    opacity: 0.6;
    ;
}

.health-follow-up {
    margin-top: 20px;
    border-top: 1px solid #e4e7ed;
    padding-top: 10px;
}

.button-group {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 20px;
}
</style>